using UnityEngine;

[RequireComponent(typeof(CharacterController))]
public class FirstPersonController : MonoBehaviour
{
    [Header("移动参数")]
    public float walkSpeed = 5f;         // 走路速度
    public float runSpeed = 9f;          // 奔跑速度
    public float gravity = -9.81f;       // 重力
    public float jumpHeight = 1.5f;      // 跳跃高度

    [Header("鼠标参数")]
    public Transform playerCamera;       // 摄像机
    public float mouseSensitivity = 100f;
    public float smoothTime = 0.05f;     // 鼠标平滑

    private CharacterController controller;
    private Vector3 velocity;
    private float xRotation = 0f;
    private Vector2 currentMouseDelta;
    private Vector2 currentMouseDeltaVelocity;

    void Start()
    {
        controller = GetComponent<CharacterController>();
        Cursor.lockState = CursorLockMode.Locked; // 锁定鼠标
    }

    void Update()
    {
        HandleLook();
        HandleMovement();
    }

    void HandleLook()
    {
        // 获取鼠标输入
        Vector2 targetMouseDelta = new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));

        // 平滑插值
        currentMouseDelta = Vector2.SmoothDamp(
            currentMouseDelta, targetMouseDelta,
            ref currentMouseDeltaVelocity, smoothTime);

        // 左右转头
        transform.Rotate(Vector3.up * currentMouseDelta.x * mouseSensitivity * Time.deltaTime);

        // 上下看
        xRotation -= currentMouseDelta.y * mouseSensitivity * Time.deltaTime;
        xRotation = Mathf.Clamp(xRotation, -80f, 80f);
        playerCamera.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
    }

    void HandleMovement()
    {
        // 获取输入
        float moveX = Input.GetAxis("Horizontal");
        float moveZ = Input.GetAxis("Vertical");

        // Shift 切换速度
        float currentSpeed = Input.GetKey(KeyCode.LeftShift) ? runSpeed : walkSpeed;

        // 方向计算（基于角色朝向）
        Vector3 move = transform.right * moveX + transform.forward * moveZ;
        controller.Move(move * currentSpeed * Time.deltaTime);

        // 判断是否在地面
        if (controller.isGrounded && velocity.y < 0)
            velocity.y = -2f;

        // 跳跃
        if (Input.GetButtonDown("Jump") && controller.isGrounded)
            velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);

        // 应用重力
        velocity.y += gravity * Time.deltaTime;
        controller.Move(velocity * Time.deltaTime);
    }
}
